<template>
	<view class="reception-page">
		<!-- 页面头部 -->
		<view class="page-header">
			<status-bar />
			<view class="header-content">
				<text class="title">售房部前台系统</text>
				<view class="user-info">
					<text class="welcome">欢迎您，{{ $userInfo.nickName }}</text>
					<button class="logout-btn" @tap="handleLogout">退出登录</button>
				</view>
			</view>
		</view>

		<!-- Tab导航 -->
		<view class="tab-navigation">
			<view class="tab-item" :class="{ active: activeTab === 0 }" @tap="switchTab(0)">
				<text class="tab-text">客户登记</text>
			</view>
			<view class="tab-item" :class="{ active: activeTab === 1 }" @tap="switchTab(1)">
				<text class="tab-text">小程序登记</text>
			</view>
			<view class="tab-item" :class="{ active: activeTab === 2 }" @tap="switchTab(2)">
				<text class="tab-text">置业顾问</text>
			</view>
		</view>

		<!-- 功能区域 -->
		<view class="main-content">
			<swiper class="swiper-box" :current="activeTab" @change="onSwiperChange"
				:style="{ height: swiperHeight + 'px' }">
				<!-- 置业顾问打卡 -->

				<!-- 客户报到 -->
				<swiper-item class="swiper-item">
					<view class="card-section">
						<view class="section-content">
							<view class="search-section">
								<uni-easyinput class="search-input" type="number" v-model="customerPhone"
									suffixIcon="scan" @iconClick="scanQrcode" placeholder="请输入客户手机号" />
								<button class="search-btn" @tap="searchCustomer">查询客户</button>
								<button class="search-btn2 btn-primary" @tap="addCustomer" v-if="searched">添加客户</button>
							</view>

							<template v-if="shopCustomerList.length && (!customerInfo || !!!customerInfo._id)">
								<view class="customer-list">
									<view class="list-header">
										<text class="list-title">售房部客户：</text>
									</view>
									<view class="customer-item" :key="shop._id" v-for="shop in shopCustomerList"
										@tap="selectShopCustome(shop)">
										<view class="customer-basic">
											<text class="customer-name">{{ shop.customerName }}</text>
											<text class="customer-phone">{{ $formatPhone(shop.phone) }}</text>
										</view>
										<view class="customer-source">
											<text>{{ getCustomerSource(shop) }} <text class="middleman-name"
													v-if="shop.middlemanName"> --
													{{ shop.middlemanName }}</text></text>
										</view>
										<view class="info-row" style="padding-top: 10rpx;" v-if="Array.isArray(shop.otherPhones) && shop.otherPhones.length">
											<text class="label">其它电话：</text>
											<text class="value schedule-time">{{shop.otherPhones.toString()}}</text>
										</view>
										<view class="info-row" style="padding-top: 10rpx;">
											<text class="label">置业顾问：</text>
											<text class="value schedule-time">{{shop.consultantName}}</text>
										</view>

										<view class="info-row">
											<text class="label">上次到访：</text>
											<text
												class="value schedule-time">{{$formatTime(shop.visitTime)}}</text>
										</view>
									</view>
								</view>
							</template>
							<!-- 客户选择列表（多个客户时显示） -->
							<view class="customer-list"
								v-if="multipleCustomers.length > 0 && (!customerInfo || !!!customerInfo._id)">
								<view class="list-header">
									<text class="list-title">报备客户：</text>
								</view>
								<view class="customer-item" v-for="(customer, index) in multipleCustomers" :key="index"
									@tap="selectCustomer(customer)">
									<view class="customer-basic">
										<text class="customer-name">{{ customer.customerName }}</text>
										<text class="customer-phone">{{ $formatPhone(customer.phone)}}</text>
									</view>
									<view class="customer-source">
										<text>{{ getCustomerSource(customer) }} <text class="middleman-name"
												v-if="customer.middlemanName"> --
												{{ customer.middlemanName }}</text></text>
									</view>
									<view class="info-row" style="padding-top: 10rpx;">
										<text class="label">报备时间：</text>
										<text
											class="value schedule-time">{{$formatTime(customer.scheduleDateTime)}}</text>
									</view>
									<!-- // <text class="search-btn" @tap.stop="cancelCustomer(customer)">置为无效</text> -->
								</view>
							</view>

							<!-- 客户信息展示 -->
							<view class="customer-info" v-if="customerInfo._id" :key="customerInfo._id">
								<view class="info-row">
									<text class="label">客户姓名：</text>
									<text class="value">{{ customerInfo.customerName }}</text>
								</view>
								<view class="info-row">
									<text class="label">联系电话：</text>
									<text class="value">{{ $formatPhone(customerInfo.phone) }}</text>
								</view>
								<view class="info-row"  v-if="Array.isArray(customerInfo.otherPhones) && customerInfo.otherPhones.length">
									<text class="label">其它电话：</text>
									<text class="value schedule-time">{{customerInfo.otherPhones.toString()}}</text>
								</view>
								<view class="info-row">
									<text class="label">来源：</text>
									<text class="value">{{ getCustomerSource(customerInfo) }} <text
											class="middleman-name" v-if="customerInfo.middlemanName">{{
												customerInfo.middlemanName }}</text></text>
								</view>
								<view class="info-row" v-if="customerInfo.middlemanName">
									<text class="label">中介公司：</text>
									<text class="value middleman-name">{{ customerInfo.middlemanName }}</text>
								</view>
								<view class="info-row" v-if="customerInfo.advisorName">
									<text class="label">原顾问：</text>
									<text class="value">{{ customerInfo.advisorName }}</text>
								</view>
								<view class="info-row" v-if="customerInfo.scheduleDateTime">
									<text class="label">报备时间：</text>
									<text class="value">{{$formatTime(customerInfo.scheduleDateTime)}}</text>
								</view>
								<view class="action-row" v-if="customerInfo.form != 'add'">
									<view class="btn-small refresh-btn" @tap="resetToSearch">重新选择</view>
								</view>
							</view>

							<!-- 分配置业顾问 -->
							<view class="assign-section" v-if="customerInfo._id">
								<view class="form-item" v-if="!customerInfo.consultantId">
									<text class="item-label">分配置业顾问</text>
									<template v-if="customerInfo.creatorType ==2">
										<text class="picker-text">{{customerInfo.advisorName}}</text>
									</template>
									<picker v-else class="item-picker" mode="selector" :range="availableConsultants"
										range-key="nickName" @change="onConsultantChange">
										<view class="picker-content">
											<text class="picker-text">{{ selectedConsultant ?
												selectedConsultant.nickName : '请选择' }}</text>
											<text class="picker-arrow">▼</text>
										</view>
									</picker>
								</view>
								<view class="form-item" v-else>
									<text class="item-label">当前置业顾问</text>


									<text class="picker-text">{{customerInfo.consultantName}}</text>
								</view>
								<view class="info-row">
									<text class="label">随行人数</text>
									<view class="info-flex">
										<uni-data-checkbox mode="tag" v-model="textNum"
											:localdata="numArr"></uni-data-checkbox>
									</view>
								</view>
								<button class="assign-btn" @tap="assignConsultant"
									:disabled="!selectedConsultant && !!!customerInfo.consultantId ">{{customerInfo.consultantId?'登记':'登记并分配' }}</button>
							</view>

							<!-- 查询结果提示 -->
							<view class="no-customer"
								v-if="searched && !customerInfo && multipleCustomers.length === 0">
								<text>未找到该客户信息</text>
							</view>
						</view>
					</view>
				</swiper-item>
				<swiper-item class="swiper-item">
					<view class="card-section">
						<view class="section-content">
							<view class="consultant-list">
								<view class="consultant-item" v-for="consultant in miniList" :key="consultant._id">
									<view class="consultant-info">
										<text class="consultant-name">{{ $formatPhone(consultant.phone) }}</text>
										<text class="consultant-status">签到时间:
											{{$formatTime(consultant.createTime)}}</text>
									</view>
									<button class="toggle-btn" size="small" @tap="addSign(consultant)">
										签到
									</button>
								</view>
								<view class="empty-state" v-if="miniList.length ==0">
									<text class="empty-icon">
										<image src="@/static/imgs/empty.png"></image>
									</text>
									<text class="empty-text">暂无签到</text>
									<!-- <button class="empty-btn" @click="addNewCustomer">添加客户</button> -->
								</view>
							</view>
						</view>
					</view>
				</swiper-item>
				<swiper-item class="swiper-item">
					<view class="card-section">
						<view class="section-content">
							<view class="consultant-list">
								<view class="consultant-item" v-for="consultant in consultantList" :key="consultant._id"
									:class="{ 'online': consultant.isOnline }">
									<view class="consultant-info">
										<text class="consultant-name">{{ consultant.nickName }}</text>
										<text class="consultant-status"
											:class="{ 'status-online': consultant.isOnline }">
											{{ consultant.isOnline ? '在岗' : '离岗' }}
										</text>
										<text class="consultant-tips">今日服务人数:<text
												class="consultant-tips-num">{{consultant.todyCustomers}}</text></text>

									</view>
									<button class="toggle-btn" :class="{ 'btn-online': consultant.isOnline }"
										size="small" @tap="toggleConsultantStatus(consultant)">
										{{ consultant.isOnline ? '下线' : '上线' }}
									</button>
								</view>
							</view>
						</view>
					</view>
				</swiper-item>


			</swiper>
		</view>

		<!-- 提示信息 -->
		<uni-popup ref="messagePopup" type="message">
			<uni-popup-message :type="messageType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>


		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" title="置为无效" cancelText="取消" confirmText="无效"
				@confirm="cancelAppore('add')">
				<view style="flex:1;width:100%" class="inputDialog-content">
					<textarea class="pop-textarewa" v-model="textArea" auto-height placeholder="请输入理由" />
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	// to do 随行人数与接待记录
	// todo 选择shopCustomer 要去刷新mid 客户的过期时间
	let time = ''
	export default {
		data() {
			return {
				activeTab: 0, // 默认显示第一个tab
				swiperHeight: 800, // swiper高度，默认值
				consultantList: [],
				customerPhone: '',
				customerInfo: {},
				shopCustomer: {},
				multipleCustomers: [], // 存储多个客户的结果
				searched: false,
				// availableConsultants: [],
				selectedConsultant: null,
				messageType: 'success',
				messageText: '',
				lastSearchPhone: '',
				miniList: [], // 存储上次搜索的手机号,
				textArea: '',
				shopCustomerList:[],
				textNum: 1,
				numArr: [{
					text: '1',
					value: 1
				}, {
					text: '2',
					value: 2
				}, {
					text: '3',
					value: 3
				}, {
					text: '4',
					value: 4
				}, {
					text: '5',
					value: 5
				}, {
					text: '6',
					value: 6
				}, {
					text: '7',
					value: 7
				}, {
					text: '8',
					value: 8
				}],
				isSearch:false
			}
		},
		computed: {
			availableConsultants() {
				let arr = this.consultantList.filter(item => item.isOnline === 1);
				arr?.map(item => {
					// item.nickName = item.nickName + '-' + item.todyCustomers
					item.showName =  item.nickName + '-' + item.todyCustomers
					return item
				})
				return arr
			}
		},
		onLoad() {
			uni.startPullDownRefresh();
			this.loadConsultantList()
		},
		onPullDownRefresh() {
			this.loadConsultantList();
			// 初始化swiper高度
			time = this.$formatYear(new Date())
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000)
		},

		mounted() {
			this.calculateSwiperHeight();
		},
		onShow(){
			this.customerPhone = ''
		},
		methods: {
			// 计算swiper高度
			calculateSwiperHeight() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.main-content').boundingClientRect(data => {
					if (data) {
						// 获取屏幕高度
						const screenHeight = uni.getSystemInfoSync().windowHeight;
						// 计算swiper高度为屏幕高度减去main-content的top位置
						this.swiperHeight = screenHeight - data.top - 30;
					}
				}).exec();
			},

			// 切换Tab
			switchTab(index) {
				this.activeTab = index;
				if (index == 1) {
					this.loadMiniSign()
				} else if (index == 2) {
					this.getConsultantCustomerNum()
				}
			},

			// swiper切换事件
			onSwiperChange(e) {
				this.activeTab = e.detail.current;
			},

			// 加载置业顾问列表
			async loadConsultantList() {
				this.resetForm()
				try {
					const res = await this.$cloudOBjAjax('sunny-users', 'getConsultantList', {});
					this.consultantList = res;
					this.getConsultantCustomerNum()
					// 获取在岗的顾问作为可分配列表
					// this.availableConsultants = res.filter(item => item.isOnline === 1);
				} catch (error) {
					console.error('加载置业顾问列表失败:', error);
					this.showMessage('加载置业顾问列表失败', 'error');
				}
			},
			getConsultantCustomerNum() {
				this.consultantList.map(item => {
					this.$cloudOBjAjax('suuny-custom', 'getZYGWcustomer', {
						userId: item._id,
						registrationDate: this.$formatYear(new Date()),
						pageSize: 1,
					}).then(res => {
						item.todyCustomers = res.total
					})
				})
			},

			// 切换置业顾问在岗状态
			async toggleConsultantStatus(consultant) {
				try {
					const res = await this.$cloudOBjAjax('sunny-users', 'toggleUserOnline', {
						userId: consultant._id
					});
					if (res) {
						// 更新本地状态
						consultant.isOnline = consultant.isOnline === 1 ? 0 : 1;
						// 更新可分配顾问列表
						this.availableConsultants = this.consultantList.filter(item => item.isOnline === 1);
						console.log('更新可分配顾问列表:', this.availableConsultants);
						this.showMessage('更新成功', 'success');
					} else {
						this.showMessage(res.errorMsg || '操作失败', 'error');
					}
				} catch (error) {
					console.error('切换顾问状态失败:', error);
					this.showMessage('操作失败', 'error');
				}
			},

			// 查询客户
			async searchCustomer() {
				if (!this.customerPhone) {
					return this.showMessage('请输入客户手机号', 'error');
				}

				// 保存搜索的手机号
				this.lastSearchPhone = this.customerPhone;

				// 验证手机号格式（支持完整手机号或后四位）
				const isFullPhone = /^1[3-9]\d{9}$/.test(this.customerPhone);
				const isLastFourDigits = /^\d{4}$/.test(this.customerPhone);
				
				if(this.customerPhone.length != 7 && this.customerPhone.length != 4 && this.customerPhone.length != 11){
					return this.showMessage('请输入正确的手机号（完整号码或后四位）', 'error');
				}
			

				// if (!isFullPhone && !isLastFourDigits) {
				// 	return this.showMessage('请输入正确的手机号（完整号码或后四位）', 'error');
				// }

				uni.showLoading({
					title: '查询中...'
				});

				try {
					let customerRes = await this.$cloudOBjAjax('suuny-custom', 'getCustomerByPhone', {
						phone: this.customerPhone
					});

					// 重置客户列表
					this.multipleCustomers = [];
					this.shopCustomerList = []
					this.shopCustomer = {};
					this.customerInfo = {}

					console.log('sunny-custom查询结果:', customerRes)
					
					
					if (customerRes && customerRes.length) {
						// 处理sunny-custom中的查询结果

						this.shopCustomerList = customerRes.map(item=>{
							item = {
								...item,
								from: 'sunny-custom'
							}
							return item
						})
						// return
						// 如果没有找到客户，继续查询middleman-advisor-customers
					}

					// 如果在sunny-custom中没有找到或找到了单个客户，再到middleman-advisor-customers中查找
					// if (!customerRes || !customerRes._id) {
					const middlemanRes = await this.$cloudOBjAjax('middleman-advisor-customers',
						'getCustomerList', {
							phone: this.customerPhone,
							isSchedule: 1,
							// scheduleTime: time
						});

					if (middlemanRes && middlemanRes.list && middlemanRes.list.length > 0) {
						this.multipleCustomers = middlemanRes.list.map(customer => ({
							...customer,
							from: 'middleman-advisor-customers'
						}));
					}
					// }


					this.searched = true;
				} catch (error) {
					console.error('查询客户失败:', error);
					this.showMessage('查询客户失败', 'error');
				} finally {
					uni.hideLoading();
				}
				console.log('customerPhone', this.customerPhone)
				if ((!this.shopCustomerList || !this.shopCustomerList.length) && this.multipleCustomers.length == 0) {
					uni.showModal({
						title: '提示',
						content: '没有找到该客户,是否直接添加客户',
						success: (res) => { // ✅ 使用箭头函数保持this上下文
							if (res.confirm) {
								uni.navigateTo({ // ✅ 正确的API名称
									url: `/pages/customer/add${isFullPhone ? '?phone=' + this.customerPhone : ''}`
								});
							}
						}
					});
				}
				
				this.searched = true
			},
			selectShopCustome(customer) {
				if (customer.isRegistration >= 1) {
					return this.$simpleToast('今日已经签到过了')
				}
				this.customerInfo = {
					...customer
				}
			},
			// 选择客户
			selectCustomer(customer) {
				
				// 
				
				const cusomerQ3 = customer.phone.substring(0,3)
				const cusomerH4 = customer.phone.substring(7)
				
				console.log(cusomerQ3,cusomerH4)
				let isHAse = false
				if (this.shopCustomerList.length) {
					this.shopCustomerList.map(item=>{
						let qian3 = item.phone.substring(0,3)
						let hou4 = item.phone.substring(7)
						
						if(item.phone === customer.phone || (cusomerQ3==qian3 && hou4==cusomerH4)){
							isHAse = true
						}
					})
				}
				if(isHAse){
					return this.$simpleToast('请选择售房部客户')
				}
				
				let scheduleDateTime = new Date(customer.scheduleDateTime).getTime()
				// 15 分钟有效
				let exTime = scheduleDateTime + (15 * 60 * 1000)
				let nowTime = new Date().getTime()
				if (exTime > nowTime) {

					uni.showModal({
						title: '提示',
						content: `报备到现在还没有15分钟,为无效客户`,
						showCancel: true,
						confirmText: '创建并到访',
						success: res => {
							if (res.confirm) {
								this.copyCustomerAndChangeStatus(customer)
							} else {
								// this.resetForm()
							}
						},
						fail: () => {},
						complete: () => {}
					});
					return
				}
				customer.form = ''

				if (customer.creatorType == 2) {
					this.selectedConsultant = {
						_id: customer.advisorId,
						nickName: customer.advisorName
					}
				}
				this.customerInfo = customer;
				this.multipleCustomers = [];
			},

			// 重新选择客户
			resetToSearch() {
				this.customerInfo = null;
				this.multipleCustomers = [];
				this.shopCustomerList = []
				// 如果之前搜索过，重新显示搜索结果
				if (this.lastSearchPhone) {
					this.customerPhone = this.lastSearchPhone;
					this.searchCustomer();
				}
			},

			// 刷新搜索
			refreshSearch() {
				if (this.customerPhone) {
					this.searchCustomer();
				}
			},

			// 获取客户来源
			getCustomerSource(customer) {
				if (customer.from === 'sunny-custom') {
					if (customer.middlemanId) {
						return '中介客户';
					} else if (customer.advisorId) {
						return '顾问客户';
					} else {
						return '自然到访';
					}
				} else if (customer.from === 'middleman-advisor-customers') {
					if (customer.creatorType == 1) {
						return '中介录入客户';
					} else if (customer.creatorType == 2) {
						return '顾问录入客户';
					}
				}
				return '自然到访';
			},

			// 选择置业顾问
			onConsultantChange(e) {
				const index = e.detail.value;
				this.selectedConsultant = this.availableConsultants[index];
			},

			// 分配置业顾问
			async assignConsultant() {
				if (!this.customerInfo) {
					return this.showMessage('请先查询客户', 'error');
				}

				console.log('this.customerInfo', this.customerInfo)

				// 如果客户之前就有置业顾问，那这里我们只签到不分配
				if (this.customerInfo.consultantId) {
					// 执行客户签到（登记）操作
					try {
						uni.showLoading({
							title: '客户签到中...'
						});

						// 添加客户登记记录到生命周期历史
						const checkInRes = await this.$cloudOBjAjax('customer-lifecycle-history', 'addFenPeiRecord', {
							customerId: this.customerInfo._id,
							customerName: this.customerInfo.customerName,
							consultantId: this.customerInfo.consultantId,
							consultantName: this.customerInfo.consultantName,
							eventType: 3, // 客户登记事件类型
							eventDescription: '客户到访签到登记',
							textNum: this.textNum,
							
						});

						if (checkInRes) {
							this.showMessage('客户签到成功', 'success');
							console.log('ssss')
							// 重置表单
							this.resetForm();
						} else {
							this.showMessage('签到失败', 'error');
						}
						this.resetForm()
					} catch (error) {
						console.error('客户签到失败:', error);
						this.showMessage('签到失败: ' + (error.errMsg || error.message || '未知错误'), 'error');
					} finally {
						uni.hideLoading();
					}
					return;
				}

				if (!this.selectedConsultant) {
					return this.showMessage('请选择置业顾问', 'error');
				}

				uni.showLoading({
					title: '分配中...'
				});

				try {
					if (this.customerInfo.from === 'middleman-advisor-customers') {
						// 如果客户在middleman-advisor-customers中，需要先创建sunny-custom记录并绑定
						const bindRes = await this.$cloudOBjAjax('middleman-advisor-customers',
							'createCustomAndBind', {
								customerId: this.customerInfo._id
							})
						if (bindRes) {
							// 绑定成功后，再分配置业顾问
							const assignRes = await this.$cloudOBjAjax('suuny-custom', 'assignConsultant', {
								customerId: bindRes.id,
								consultantId: this.selectedConsultant._id,
								consultantName: this.selectedConsultant.nickName
							});
							// 添加绑定生命周期
							this.$cloudOBjAjax('customer-lifecycle-history', 'midBindCustomer', {
								mid_id: this.customerInfo._id,
								customerId: bindRes.id
							})

							await this.$cloudOBjAjax('customer-lifecycle-history', 'addFenPeiRecord', {
								customerId: bindRes.id,
								customerName: this.customerInfo.customerName,
								// consultantId: this.selectedConsultant._id,
								// consultantName: this.selectedConsultant.nickName,
								textNum: this.textNum,
								eventType: 3, // 客户登记事件类型
								eventDescription: `客户到访签到登记,随行人数:${this.textNUm}`
							});

							await this.$cloudOBjAjax('customer-lifecycle-history', 'addFenPeiRecord', {
								customerId: bindRes.id,
								customerName: this.customerInfo.customerName,
								consultantId: this.selectedConsultant._id,
								consultantName: this.selectedConsultant.nickName,
								eventType: 4, // 客户登记事件类型
								eventDescription: '分配客户'
							});

							// 添加登记生命周期

							// 添加分配生命周期
							if (assignRes) {
								this.showMessage('分配成功', 'success');
								// 重置表单
								this.resetForm();
							} else {
								this.showMessage(assignRes.message || '分配失败', 'error');
							}
						} else {
							this.showMessage(bindRes.message || '绑定失败', 'error');
						}
					} else {


						const assignRes = await this.$cloudOBjAjax('suuny-custom', 'assignConsultant', {
							customerId: this.customerInfo._id,
							consultantId: this.selectedConsultant._id,
							consultantName: this.selectedConsultant.nickName
						});

						await this.$cloudOBjAjax('customer-lifecycle-history', 'addFenPeiRecord', {
							customerId: this.customerInfo._id,
							customerName: this.customerInfo.customerName,
							consultantId: this.selectedConsultant._id,
							consultantName: this.selectedConsultant.nickName,
							eventType: 3, // 客户登记事件类型
							eventDescription: '客户到访签到登记'
						});

						await this.$cloudOBjAjax('customer-lifecycle-history', 'addFenPeiRecord', {
							customerId: this.customerInfo._id,
							customerName: this.customerInfo.customerName,
							consultantId: this.selectedConsultant._id,
							consultantName: this.selectedConsultant.nickName,
							eventType: 4, // 客户登记事件类型
							eventDescription: '分配客户'
						});


						// 添加分配生命周期
						if (assignRes) {
							this.showMessage('分配成功', 'success');
							// 重置表单
							this.resetForm();
						} else {
							this.showMessage(assignRes.message || '分配失败', 'error');
						}
					}
				} catch (error) {
					console.error('分配顾问失败:', error);
					this.showMessage('分配失败', 'error');
				} finally {
					uni.hideLoading();
				}
			},

			// 重置表单
			resetForm() {
				this.customerPhone = '';
				this.multipleCustomers = []
				this.shopCustomerList = []
				this.isSearch = false
				this.shopCustomer = {}
				this.customerInfo = {};
				this.searched = false;
				this.selectedConsultant = {};
			},

			// 显示消息提示
			showMessage(message, type = 'success') {
				this.messageType = type;
				this.messageText = message;
				this.$refs.messagePopup.open();
			},

			// 退出登录
			handleLogout() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							// 清除用户信息
							uni.removeStorageSync('userInfo');
							// 跳转到登录页
							uni.redirectTo({
								url: '/pages/login/login'
							});
						}
					}
				});
			},
			scanQrcode() {
				this.resetForm()
				// #ifndef H5
				uni.scanCode({
					scanType: ['qrCode'],
					onlyFromCamera: true,
					success: res => {
						let result = res.result
						this.getCustomerByShechedNo(result)
					},
					fail: err => {
						return this.$simpleToast(err.errMsg)
					}
				})
				// #endif

				// this.getCustomerByShechedNo('c62247e413594693232')
				// this.getCustomerByShechedNo('04ae34ca13212341234')
			},
			copyCustomerAndChangeStatus(customer) {
				
				console.log('customer',customer)
				let newCustomer = {
					customerName: customer.customerName,
					phone: customer.phone,
					status: 1,
					gender: customer.gender,
					address: customer.address,
					company: customer.company,
					job: customer.job,
					idCard: customer.idCard,
					childrenCount: customer.childrenCount,
					weixin: customer.weixin,
					marriage: customer.marriage,
					income: customer.income,
					familyStatus: customer.familyStatus,
					typeMap: 1
				}
				
				if(customer.scheduleType == 1 && customer.schedulePhone){
					newCustomer.phone = customer.schedulePhone
					// sunnyCustomData.realPhone = customerInfo.phone
				}
				
				this.$cloudOBjAjax('suuny-custom', 'addCustomer', {
					...newCustomer
				}).then(res => {
					newCustomer.form = 'add'
					this.customerInfo = {
						...newCustomer,
						_id: res.id
					}
				})

				this.$cloudOBjAjax('middleman-advisor-customers', 'cancelCustomer', {
					id: customer._id
				})
			},
			cancelCustomer(customer) {
				// uni.show
				let des =
					`${customer.middlemanName || customer.advisorName}的客户:${customer.customerName},报备时间为:${this.$formatTime(customer.scheduleDateTime)},售房部创建时间为${this.$formatTime(this.shopCustomer.createTime)},报备时间不足15分钟,置为无效`
				this.textArea = des
				this.$refs.inputDialog.open()

				// this.$cloudOBjAjax('middleman-advisor-customers','cancelCustomer',{san
				// 	id:customer._id,
				// 	eventDescription: des,
				// })
			},
			cancelFun() {
				let ttet = this.textArea
				if (ttet) {
					return this.$simpleToast('请输入理由')
				}
				this.$cloudOBjAjax('middleman-advisor-customers', 'cancelCustomer', {
					id: customer._id,
					eventDescription: ttet,
				})
			},
			async getCustomerByShechedNo(scheduleNo) {
				const mid = await this.$cloudOBjAjax('middleman-advisor-customers', 'getCustomer', {
					scheduleNo: scheduleNo
				}).catch(err => {
					return this.$simpleToast('二维码不对')
				})

				if (mid && mid.phone) {
					const shopCustomerList = await this.$cloudOBjAjax('suuny-custom', 'getCustomerByPhone', {
						phone: mid.phone
					})
					if (shopCustomerList && shopCustomerList.length) {
						this.shopCustomerList = shopCustomerList
					}else{
						this.shopCustomerList = []
					}
				}
				mid.from = 'middleman-advisor-customers'
				this.multipleCustomers = [mid]
			},
			loadMiniSign() {
				const time = this.$formatYear(new Date())
				this.$cloudOBjAjax('customer-mini-sign', 'queryList', {
					pageNo: 1,
					pageSize: 100,
					isUse: 1,
					schedule_time: time
				}).then(res => {
					this.miniList = res.list
				})
			},
			addSign(item) {
				this.customerPhone = item.phone
				this.activeTab = 0
				this.searchCustomer()
				this.$cloudOBjAjax('customer-mini-sign', 'updateSign', {
					_id: item._id,
					isUse: 2
				}).then(res => {
					this.miniList = res.list
				})
			},
			addCustomer(){
				uni.navigateTo({ // ✅ 正确的API名称
					url: `/pages/customer/add`
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.reception-page {
		min-height: 100%;
		background: #f5f6fa;
	}

	.page-header {
		background-size: 100%;
		padding: 30rpx 20rpx;
		color: white;
	}

	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.user-info {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.welcome {
		font-size: 28rpx;
		margin-bottom: 16rpx;
	}

	.logout-btn {
		background: rgba(255, 255, 255, 0.2);
		color: white;
		border: none;
		border-radius: 8rpx;
		padding: 0rpx 24rpx;
		font-size: 24rpx;
	}

	/* Tab导航样式 */
	.tab-navigation {
		display: flex;
		background: white;
		margin: 0 30rpx;
		border-radius: 16rpx 16rpx 0 0;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 30rpx 0;
		background: #f8f9fa;
		transition: all 0.3s;
	}

	.tab-item.active {
		background: white;
		border-bottom: 6rpx solid #667eea;
	}

	.tab-text {
		font-size: 30rpx;
		color: #666;
		font-weight: 500;
	}

	.tab-item.active .tab-text {
		color: #667eea;
		font-weight: 600;
	}

	.main-content {
		padding: 0 30rpx 30rpx;
		flex: 1;
	}

	.swiper-box {
		flex: 1;
	}

	.swiper-item {
		height: 100%;
	}

	.card-section {
		background: white;
		border-radius: 0 0 16rpx 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		height: 100%;
	}

	.section-header {
		padding: 30rpx;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.section-content {
		padding: 30rpx;
		height: calc(100% - 100rpx);
		overflow-y: auto;
	}

	/* 置业顾问列表样式 */
	.consultant-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.consultant-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		background: #fafafa;
		transition: all 0.3s;
	}

	.consultant-item.online {
		border-color: #4cd964;
		background: #f0fff4;
	}

	.consultant-info {
		display: flex;
		flex-direction: column;
		flex: 1;
	}

	.consultant-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
	}

	.consultant-tips {
		font-size: 22rpx;
		color: #999;

		.consultant-tips-num {
			font-size: 30rpx;
			color: rgba(33, 117, 255, 1);
		}
	}

	.consultant-status {
		font-size: 24rpx;
		color: #999;
	}

	.consultant-status.status-online {
		color: #4cd964;
	}

	.toggle-btn {
		background: #667eea;
		color: white;
		border: none;
		border-radius: 8rpx;
		padding: 0 24rpx;
		font-size: 24rpx;
	}

	.toggle-btn.btn-online {
		background: #ff4757;
	}

	/* 客户查询样式 */
	.search-section {
		display: flex;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.search-input {
		flex: 1;
	}

	.search-btn {
		background: linear-gradient(135deg, #FFA500 0%, #FF8C00 100%);
		color: white;
		border: none;
		border-radius: 4px;
		padding: 0 15px;
		font-size: 14px;
		line-height: 35px;
		height:35px;
	}
	
	.search-btn2 {
		color: white;
		border: none;
		border-radius: 4px;
		padding: 0 15px;
		font-size: 14px;
		line-height: 35px;
		height:35px;
	}

	/* 客户信息样式 */
	.customer-info {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
	}

	.info-row {
		display: flex;
		margin-bottom: 16rpx;

		.info-flex {
			display: flex;
			flex: 1;
			padding-left: 30rpx;
			justify-content: flex-end;

		}
	}

	.info-row:last-child {
		margin-bottom: 0;
	}

	.action-row {
		display: flex;
		justify-content: flex-end;
		margin-top: 20rpx;
	}

	.label {
		font-size: 26rpx;
		color: #666;
		// width: 180rpx;
	}

	.value {
		font-size: 26rpx;
		color: #333;
		flex: 1;
	}

	/* 客户选择列表样式 */
	.customer-list {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
		max-height: 400rpx;
		overflow-y: auto;
	}

	.list-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.list-title {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		display: block;
	}

	.refresh-btn {
		background: #667eea;
		color: white;
		border: none;
		border-radius: 8rpx;
		padding: 10rpx 20rpx;
		font-size: 24rpx;
	}

	.customer-item {
		padding: 20rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		background: white;
		margin-bottom: 20rpx;
	}

	.customer-item:last-child {
		margin-bottom: 0;
	}

	.customer-basic {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.customer-name {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.customer-phone {
		font-size: 26rpx;
		color: #666;
	}

	.customer-source {
		font-size: 24rpx;
		color: #999;
	}

	.middleman-name {
		color: #FF8C00;
		/* 橙色，突出显示中介名称 */
		font-weight: bold;
	}

	/* 分配顾问样式 */
	.assign-section {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
	}

	.form-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;
	}

	.form-item:last-child {
		margin-bottom: 0;
	}

	.item-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

	.picker-content {
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		padding: 20rpx 24rpx;
		background: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
	}

	.picker-text:placeholder {
		color: #999;
	}

	.picker-arrow {
		color: #999;
		font-size: 24rpx;
	}

	.assign-btn {
		background: linear-gradient(135deg, #FFA500 0%, #FF8C00 100%);
		color: white;
		border: none;
		border-radius: 12rpx;
		font-size: 30rpx;
		font-weight: 600;
		height: 60rpx;
		line-height: 60rpx;
	}

	.assign-btn:disabled {
		opacity: 0.6;
	}

	/* 无客户提示 */
	.no-customer {
		text-align: center;
		padding: 40rpx;
		color: #999;
		font-size: 28rpx;
	}

	.schedule-time {
		color: red;
	}
	
	@media screen and (min-width: 750px) {
		::v-deep .uni-easyinput__content-input {
			height: 50rpx;
			font-size:20rpx;
		}
		
		.search-btn {
			height: 50rpx;
			line-height: 50rpx;
		}
		
		.search-btn2 {
			height: 50rpx;
			line-height: 50rpx;
		}
	}
</style>